import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/cate.vue'
import Params from '../components/goods/Params.vue'
// 希望Welcome这个组件是以子路由规则的形式存在于home这个规则中,因为home页面中要嵌套着显示欢迎页面
// 先导入组件,然后在路由中新增一个路由规则

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome},
      { path: '/user', component: Users},
      { path: '/privilege', component: Rights},
      { path: '/log', component: Roles},
      { path: '/device', component: Cate},
      { path: '/system', component: Params}
    ]
  } // 如果用户没有登录,直接通过url访问特定的页面,需要重新导航到登录页面,这时候需要导航控制守卫重定向
]

const router = new VueRouter({
  routes
})

// to代表将要访问的地址,from代表从哪个地址而来,next代表放行的函数,判断to代表的地址是否是/login
router.beforeEach((to, from, next) => {
  // 如果用户访问呢的是登录页,直接放行,next('/login'),这个是强制跳转
  if (to.path === '/login') return next()
  // 先获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
